package net.mikoo.seals.boss.biz.services.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import net.mikoo.seals.boss.biz.mapper.client.DevicesMapper;
import net.mikoo.seals.boss.biz.mapper.client.DevicesModelMapper;
import net.mikoo.seals.boss.biz.services.DevicesServices;
import net.mikoo.seals.boss.common.BaseServices;
import net.mikoo.seals.boss.common.PageModel;
import net.mikoo.seals.boss.common.enums.DevicesStatusEnum;
import net.mikoo.seals.boss.common.exception.ParametersException;
import net.mikoo.seals.boss.model.Devices;
import net.mikoo.seals.boss.model.DevicesQuery;
import net.mikoo.seals.boss.model.DevicesRenew;

@Service
public class DevicesServicesImpl extends BaseServices implements DevicesServices {

	Logger logger = LoggerFactory.getLogger(CompanyServicesImpl.class);

	@Autowired
	private DevicesMapper devicesMapper;
	
	@Autowired
	private DevicesModelMapper devicesModelMapper;

	@Override
	public void save(Devices devices) {

		if (devices == null) {
			throw new ParametersException("devices is null!");
		}

		if (StringUtils.isBlank(devices.getDevicesCode())) {
			throw new ParametersException("请输入设备编号");
		}
		
		if(StringUtils.isBlank(devices.getModel())) {
			throw new ParametersException("请选择模型");
		}
		
		//String model = devices.getModel();
		//DevicesModel devicesModel = devicesModelMapper.selectInfoById(model);

		devices.setUseTimes(0);
		devices.setApplyTimes(0);
		devices.setDevicesStatus(DevicesStatusEnum.INIT.code());
		devices.setCreateTime(new Date());
		
		//devices.setDevicesVerson(devicesModel.getVersion());
		//devices.setNetwork(devicesModel.getNetwork());
		devicesMapper.insert(devices);
	}

	@Override
	public void modify(Devices devices) {

		if (devices == null) {
			throw new ParametersException("devices is null!");
		}
		devicesMapper.update(devices);
	}

	@Override
	public Devices getInfoById(Long DevicesId) {

		if (DevicesId == null) {
			throw new ParametersException("DevicesId is null!");
		}

		Devices Devices = devicesMapper.selectInfoById(DevicesId);
		return Devices;
	}

	@Override
	public PageModel<Devices> getPageByQuery(DevicesQuery query) {

		List<Devices> datas = devicesMapper.selectByQueryToPage(query);
		Integer total = devicesMapper.countByQueryToPage(query);
		PageModel<Devices> pm = new PageModel<Devices>(total, datas);
		return pm;
	}

	@Override
	public void deleteById(Devices devices) {

		if (devices == null) {
			throw new ParametersException("devices is null");
		}

		if (devices.getDevicesId() == null) {
			throw new ParametersException("devicesId is null");
		}

		devicesMapper.deleteById(devices);
	}

	@Override
	public void deserted(Devices devices) {

		if (devices == null) {
			throw new ParametersException("devices is null");
		}

		if (devices.getDevicesId() == null) {
			throw new ParametersException("devicesId is null");
		}

		Devices exist = devicesMapper.selectInfoById(devices.getDevicesId());
		if (exist == null) {
			throw new ParametersException("此设备不存在");
		}
		
//		String code = exist.getDevicesCode();
//		int index = code.indexOf("_");
//		if(index>0) {
//			String oldCode = code.substring(0, index);
//			String numstr = code.substring(index+1, code.length());
//			int num = Integer.parseInt(numstr)+1;
//			exist.setDevicesCode(oldCode.concat("_").concat(num+""));
//			
//		}else {
//			exist.setDevicesCode(code.concat("_").concat("1"));
//		}
		
		//2

		this.clientTransactionTemplate.execute(new TransactionCallbackWithoutResult() {

			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {

				try {
					devices.setDevicesCode(exist.getDevicesCode()+"-fq");
					devices.setDevicesStatus(DevicesStatusEnum.DESERTED.code());
					devices.setVersion(exist.getVersion());
					devicesMapper.updateChangeStatus(devices);
					
					Devices info = devicesMapper.selectInfoByCode(exist.getDevicesCode());
					if(info != null) {
						throw new ParametersException("此设备编码已存在");
					}

					exist.setDevicesId(null);
					exist.setDevicesStatus(DevicesStatusEnum.INIT.code());
					devicesMapper.insert(exist);
				} catch (Exception e) {

					status.setRollbackOnly();
					throw e;
				}

			}
		});

	}

	@Override
	public void alloacation(Long companyId, List<Long> devicesIds) {

		if (companyId == null) {
			throw new ParametersException("请选择公司");
		}

		if (devicesIds == null || devicesIds.isEmpty()) {
			throw new ParametersException("请选择设备");
		}
		this.clientTransactionTemplate.execute(new TransactionCallbackWithoutResult() {

			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				try {

					for (Long devicesId : devicesIds) {
						Devices devices = devicesMapper.selectInfoById(devicesId);

						if (devices == null) {
							throw new ParametersException("此设备不存在");
						}

						if (!devices.getDevicesStatus().equals(DevicesStatusEnum.INIT.code())) {
							throw new ParametersException("此设备不处于初始化状态");
						}

						devices.setCompanyId(companyId);
						devices.setDevicesStatus(DevicesStatusEnum.WAIT_BIND.code());
						devices.setBindingTime(new Date());
						devicesMapper.update(devices);
					}

				} catch (ParametersException e) {
					status.setRollbackOnly();
					throw e;
				} catch (Exception e) {
					status.setRollbackOnly();
					throw e;
				}

			}
		});

	}

	@Override
	public void renew(DevicesRenew renew) {
		if (renew == null) {
			throw new ParametersException("renew is null");
		}

		if (renew.getDevicesId() == null) {
			throw new ParametersException("DevicesId is null");
		}

		if (renew.getRenewTime() == null) {
			throw new ParametersException("请选择日期");
		}

		Devices exist = devicesMapper.selectInfoById(renew.getDevicesId());
		if (exist == null) {
			throw new ParametersException("设备不存在");
		}
		if(exist.getIsActivate().equals("N")) {
			throw new ParametersException("请先设备还未激活，不能续签");
			
		}

		this.clientTransactionTemplate.execute(new TransactionCallbackWithoutResult() {

			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				try {
					exist.setExpireDate(renew.getRenewTime());
					devicesMapper.update(exist);

					renew.setCompanyId(exist.getCompanyId());
					renew.setCreateTime(new Date());

					devicesMapper.insertRenew(renew);

				} catch (Exception e) {
					status.setRollbackOnly();
					throw e;
				}

			}
		});

	}

	@Override
	public void changeActivateState(Devices devices) {
		if(devices == null) {
			throw new ParametersException("设备不存在");
		}
		
		if(devices.getDevicesId() == null) {
			throw new ParametersException("DevicesId is null");
		}
		
		Devices exist = devicesMapper.selectInfoById(devices.getDevicesId());
		if (exist == null) {
			throw new ParametersException("设备不存在");
		}
		String isActivate = exist.getIsActivate();
		if(isActivate.equals("Y")) {
			exist.setIsActivate("N");
			devicesMapper.update(exist);
		}else {
			exist.setIsActivate("Y");
			devicesMapper.update(exist);
		}
		
	}
	
	public static void main(String[] args) {
		String a = "213453212343213_1";
		
		int b = a.indexOf("_");
		
		System.out.println(a.substring(b+1, a.length()));
	}

}
